package org.fund.base_service.service.impl;

import org.fund.base_service.domain.Position;
import org.fund.base_service.mapper.FundValueMapper;
import org.fund.base_service.mapper.PositionMapper;
import org.fund.common.model.FundValue;
import org.fund.common.model.FundValueEntity;
import org.fund.common.util.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author:
 * @Date: 2022/3/23 15:06
 * @Description:  基金临时表 用于存放当日净值和当日前一天净值
 */
@Service
public class TempFundService {
    @Autowired
    private FundValueMapper fundValueMapper;


    @Autowired
    private PositionMapper positionMapper;
    @Autowired
    private FundService fundService;

    /**
     * 插入临时数据
     */
    public  void batchInsert(){
        // 如果是节假日或者周末就不计算收益
        String currentDay = DateUtils.getCurrentDay();
        if (DateUtils.isHolidayAndWeekend(currentDay)==0){
            return ;
        }
        List<Position> fundCodes = positionMapper.getAllFundCodeAndNames();
        List<FundValueEntity> list = new ArrayList<>(fundCodes.size());
        for (Position p : fundCodes) {
            FundValueEntity entity = getFundValueEntity(p);
            list.add(entity);
        }
        fundValueMapper.batchInsert(list);
    }

    private FundValueEntity getFundValueEntity(Position p) {
        FundValue value = fundService.lsjz(p.getFundCode());
        FundValueEntity entity  = new FundValueEntity();
        BeanUtils.copyProperties(value,entity);
        entity.setFundCode(p.getFundCode());
        entity.setFundName(p.getFundName());
        return entity;
    }

    /**
     * 获取净值
     * @param date
     * @return
     */
    public Map<String, FundValueEntity> queryByFundCodeAndDate(String date){
        List<FundValueEntity> fundEstimates = fundValueMapper.queryByFundCodeAndDate(date);
        return fundEstimates.stream().collect(Collectors.toMap(FundValueEntity::getFundCode,item->item));
    }


    /**
     * 删除指定日期的净值
     */
    public void batchDelete(){
        // 如果是节假日或者周末就不删除
        if (DateUtils.isHolidayAndWeekend(DateUtils.getCurrentDay())==0){
            return ;
        }
        fundValueMapper.batchDeleteByDate(DateUtils.getBeforeYesterday());
    }
}
